package j2024.j202407;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

public class j0714 {
    //1926
    int[] dx = new int[]{0,0,-1,1};
    int[] dy = new int[]{1,-1,0,0};
    public int nearestExit(char[][] maze, int[] entrance) {
        boolean[][] vis = new boolean[101][101];
        int step = 0;
        Queue<int[]> q = new LinkedList<>();
        int xs = maze.length;
        int ys = maze[0].length;
        q.add(new int[]{entrance[0],entrance[1]});
        vis[entrance[0]][entrance[1]] = true;
        while (!q.isEmpty()){
            step++;
            int sz = q.size();
            for (int i = 0; i < sz; i++) {
                int[] s = q.poll();
                int a = s[0],b = s[1];
                for (int j = 0; j < 4; j++) {
                    int x = a + dx[j];
                    int y = b + dy[j];
                    if(x>=0 && x<xs && y>=0 && y<ys && !vis[x][y] && maze[x][y]=='.'){
                        //判断是否到出口
                        if(x==0 || x==xs-1 || y==0 || y==ys-1){
                            return step;
                        }
                        q.add(new int[]{x,y});
                        vis[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }

    //433
    public int minMutation(String startGene, String endGene, String[] bank) {
        HashSet<String> vis = new HashSet<>();
        HashSet<String> ban = new HashSet<>();
        char[] change = {'A','C','G','T'};
        for(String i:bank){
            ban.add(i);
        }
        if(startGene.compareTo(endGene)==0){
            return 0;
        }
        if(!ban.contains(endGene)){
            return -1;
        }
        Queue<String> q = new LinkedList<>();
        q.add(startGene);
        vis.add(startGene);
        int step = 0;
        while(!q.isEmpty()){
            step++;
            int sz = q.size();
            while(sz--!=0){
                String t = q.poll();
                for (int i = 0; i < 8; i++) {
                    char[] s = t.toCharArray();
                    for (int j = 0; j < 4; j++) {
                        s[i] = change[j];
                        String a = new String(s);

                        if(ban.contains(a) && !vis.contains(a)){
                            if(a.compareTo(endGene)==0){
                                return step;
                            }
                            q.add(a);
                            vis.add(a);
                        }
                    }
                }
            }
        }
        return -1;
    }
}
